/**
 * 
 * @authors Riche
 * @date    2017-04-13 10:39:22
 * @version 1.2.0
 */


//var dataID = $.getUrlVar("id");

var info = new Vue({
    el: "#app",
    data: {
        tabs: 0,
        reqOut: false, //判断请求数据是否已完
        cartInfo:[],
        cartList:{
          isLoading:true,
          pageSize:PAGESIZE,
          pageIndex:1
        },
        selectcount:[],
        chooseAllFlag:false
    },
    created: function() {
        var dtd = $.Deferred();
        var _self = this;
        /*
        //问题列表
        var data = {
            sortType: 1,
            pageSize: _self.pageSize,
            pageIndex: _self.pageIndex
        };
        data = Common.jsonEncode(data);
        Common.ajaxCall({ url: 'ask_getQuestionList', datatype: 'json', type: 'get', data: data }, function(data) {
            if (data.error_code == 0) {
                _self.quesList = data.data;;
            } else {
                alert(data.msg);
            }
        });
        */
        //myJS.init();
    },
    compiled: function() {
        var _self = this;
        //_self.userSideFn();
        $(document).scroll(function() {
            var docHeight = $(document).height(),
                winHeight = $(window).height();
            if ((docHeight > winHeight)&&($(document).scrollTop() >= docHeight - winHeight)) {
                if (!_self.reqOut) {
                    _self.reqOut = true;
                    var str = '<img class="loading-img" src="images/loading.gif"></img>';
                    myLoad.pullLoad('quesCont', str);
                    info.loadlist(_self.tabs);
                }
            }
        });

        $(document).on('change.inputText', '.fillInput', function() {
            _self.inputText = $(this).val();
        });

        // 比例
        myJS.imgScale('.j_6', '6', '5');
        myJS.ImgFull('.loadImg', 'images/liby.png');

        /*$(document).on('click','.check',function(e){
          if($(e.target).hasClass('checkOn')){
            $(e.target).removeClass('checkOn');
          }else{
            $(e.target).addClass('checkOn');
          }
        });*/

        _self.slides(_self.tabs);
    },
    computed: {
      totalPrice: function(){
        var totalPrice = 0;
        var _self = this;
        this.cartInfo.forEach(function(item,index){
          if(item.checked){
          totalPrice += (_self.cartInfo[index].price*_self.cartInfo[index].selectcount);
          }
        })
        return totalPrice;
      }
      
    },
    /*ready:function(){
      this.loadPhoto();
    },*/
    methods: {
        loadlist: function(tabs) {
            var _self = this;
            var vModal, target; //用来储存不同的tab页面对应的对象
            var url = 'user_getCartGoodsList';
            
            vModal = _self.cartList;
            target = _self.cartInfo;

            if (!vModal.isLoading) return;
            Common.ajaxCall({ url: url, datatype: 'json', type: 'post' }, function(data) {
                if (data.error_code == 0 && data.data.length > 0) {
                    if (vModal.pageIndex == 1) {
                        target.length = 0;
                    }
                    for (var i = 0; i < data.data.length; i++) {
                        target.push(data.data[i]);
                    }
                    _self.reqOut = false;

                    //实际数据与请求的数据量比较
                    if (data.data.length >= vModal.pageSize) {
                        myLoad.pullHide(); //加载后，把效果去掉
                    } else {
                        _self.reqOut = true;
                        myLoad.noDate(); //暂无数据
                        vModal.isLoading = false;
                    }
                } else {
                    _self.reqOut = true;
                    myLoad.noDate(); //暂无数据
                    vModal.isLoading = false;
                }

                vModal.pageIndex++;
            });

        },
        selectedGood:function(item){
          var _self = this;
          var selectedNum = 0;
          if(typeof item.checked === "undefined"){
            Vue.set(item,"checked",true);
          }else{
            item.checked = !item.checked;
          }

          _self.cartInfo.forEach(function(item,index){
            if(item.checked){
              selectedNum++; 
            }
          })
          if(selectedNum === this.cartInfo.length){
            _self.chooseAllFlag = true;
          }else{
            _self.chooseAllFlag = false;
          }
        },
        chooseAll:function(){   //全选
          var _self = this;
          _self.chooseAllFlag = !_self.chooseAllFlag;
          //if(_self.chooseAllFlag){
            _self.cartInfo.forEach(function(item,index){
              if(typeof item.checked === "undefined"){
                Vue.set(item,"checked",_self.chooseAllFlag);
              }else{
                item.checked = _self.chooseAllFlag;
              }
            })
          //}else{
            
          //}
        },
        slides: function(index, e) {
            var _self = this;
            _self.tabs = index;

            if (e && typeof(e) != 'undefined') {
                $(e.currentTarget).addClass('on').siblings().removeClass('on');
            }
            
            //var str = '<img class="loading-img" src="images/loading.gif"></img>';
            //myLoad.pullLoad('quesCont', str);
            myLoad.pullHide();
            _self.quesList = []; //清空上一次请求vm储存的数据
            _self.reqOut = false;
            if (index === 2) { //调用分类接口
                _self.screen();
            } else { //调用问题列表
                var data = {
                    isLoading: true,
                    pageSize: PAGESIZE,
                    pageIndex: 1
                };
                _self = $.extend(_self, data);

                _self.loadlist(_self.tabs);
            }
            if (_self.tabs <= 3) {
                $.setCookie('askingtabs', _self.tabs); //保存最近的Tab
            }
        },
        loadPhoto: function() {
            // 比例
            myJS.imgScale('.j_1', '1', '1');
            myJS.ImgFull('.loadImg', 'images/liby.png');
        },
        decrease: function(e,index) {
            var _self = this;
            if($(e.target).hasClass('disable')) return;
            _self.cartInfo[index].selectcount--;
        },
        increase: function(e,index) {
            var _self = this;
            if($(e.target).hasClass('disable')) return;
            _self.cartInfo[index].selectcount++;
        },
        overNum:function(item){
          if(item.selectcount>item.count){
            item.selectcount = item.count;
            alert('超出库存！');
          }
        },
        toOrder: function() {  //去兑换
            var _self = this,
                orderGoods = [];
            var d = new Date();
            var selectedGoods = _self.$el.querySelectorAll(".check.checkOn");
          if(selectedGoods.length>0){
            var arrId = [];
            [].forEach.call(selectedGoods,function(val,index){
              var selectGoodId = $(val).parents('li').data('id');
              var selectcount = _self.cartInfo[index].selectcount;
              arrId.push(selectGoodId + ',' + selectcount);
            });
            window.location.href = "orderSubmit.html?buyNow=false&goodsCollection="+arrId.join(';') + "&order=" + d.getTime();

            /*Common.ajaxCall({ url: 'user_getGoodsListByIds', datatype: 'json', type: 'post', data: data}, function (data) {
              if(data.error_code==0){
                $(e.target).parents('li').remove();
              }else{
                  alert(data.msg);
              }
            })*/
          }else{
            alert('您还没有选择商品哦！');
          }
        },
        del: function(item){  //删除商品
          var _self = this;
            alert({
              text:'<span class="db padTB40 font26">确认要删除该商品吗？</span>',
              kind:2,
              close:false,
              okEvent:function(){
                var data = {
                  goodsID:item.id
                };
                Common.ajaxCall({ url: 'user_delCart', datatype: 'json', type: 'post', data: data}, function (data) {
                  if(data.error_code==0){
                    //$(e.target).parents('li').remove();
                    _self.cartInfo.$remove(item);
                  }else{
                      alert(data.msg);
                  }
                })
              }
            });
        },
        swipeLeft: function(e) {
            var _self = this;

            var shareColl = $(e.target).parents('li');
            var touchDrift = ($(e.target).parents('li').width()) / 3;
            var drift = ($(e.target).parents('li').width()) / 6;
            //回复原位置
            _self.isDrift = false; //标识为非左滑状态
            $(e.target).parents('ul').children().animate({ left: 0 });
            $(e.target).parents('ul').children().find('.shareColl').animate({ width: 0, right: 0 });


            console.log(e.deltaX);
            if (e.deltaX < 0) { //左滑
                _self.isDrift = true; //标识为左滑状态
                if (e.deltaX < -touchDrift) {
                    $(e.target).parents('li').animate({ left: -drift });
                    var height = $(e.target).parents('li').outerHeight();
                    shareColl.find('.shareColl').animate({ width: drift, right: -drift }).show().css('line-height', height + 'px');
                }
            } else { //右滑
                if (e.deltaX > touchDrift) {
                    _self.isDrift = false; //标识为非左滑状态
                    $(e.target).parents('li').animate({ left: 0 });
                    shareColl.find('.shareColl').fadeOut();

                }
            }
        },
    },
    watch: {
        "cartInfo": function() {
            this.loadPhoto();
        }
    }

});